﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;

[RequireComponent(typeof(Image))]
public class DragObj : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {

	public Vector2 standardRev = new Vector2 (1920, 1080);

	public Vector2 initPos = Vector2.zero;
	public Vector2 destPos = Vector2.one;
	Vector2 range = new Vector2(100,100);

	public GameObject FingerBg = null;
	public FingerMove finger = null;


	public Action onDragEndCallback = null;


	public Vector2 size = Vector2.one;

	public RectTransform rectTransform = null;


	// Use this for initialization
	void Start () {

	}

	// 设定参数
	public void Init( Vector2 size, Vector2 beginPos, Vector2 endPos, Action cb )
	{

		// 分辨率适配
		Debug.Log("resolution :" + Screen.width+ ", " + Screen.height);
		float fx = Screen.width * 1f / standardRev.x;
		float fy = Screen.height * 1f / standardRev.y;

//		initPos = new Vector2 (beginPos.x * fx, beginPos.y * fy);
//		destPos = new Vector2 (endPos.x * fx, endPos.y * fy);
		this.size = size; 

		this.initPos = beginPos;
		this.destPos = endPos;

		rectTransform.sizeDelta = this.size;
		rectTransform.anchoredPosition = initPos;


		finger.Begin (initPos + new Vector2(this.size.x/2f, 0-this.size.y/2f), destPos);
		ShowFinger (true);
		onDragEndCallback = cb;
	}

	void OnEnable()
	{
		rectTransform.sizeDelta = this.size;
		rectTransform.anchoredPosition = initPos;

		ShowFinger (true);
	}

		

	void OnEnd()
	{
		if (Functions.isNear (destPos, rectTransform.anchoredPosition, range)) {
		
			// next
			rectTransform.anchoredPosition = destPos;

			if (onDragEndCallback != null)
				onDragEndCallback ();

		} else {
		
			rectTransform.anchoredPosition = initPos;
			ShowFinger (true);
		}
	}


	public void OnBeginDrag(PointerEventData eventData)
	{
		ShowFinger (false);
	}

	public void OnDrag(PointerEventData eventData)
	{

		rectTransform.position = eventData.position;
		Debug.Log (rectTransform.position);
	}

	public void OnEndDrag(PointerEventData eventData)
	{
		OnEnd ();
	}


	public void ShowFinger( bool show )
	{
		finger.gameObject.SetActive (show);
		FingerBg.SetActive (show);
	}

}
